package com.sanshui.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sanshui.base.BaseResponse;
import com.sanshui.base.LoginEnum;
import com.sanshui.base.ResultUtils;
import com.sanshui.model.entity.User;
import com.sanshui.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import static com.sanshui.base.LoginEnum.loginStatic;

@RestController
@RequestMapping("user/")
@Api(tags = "用户")
public class UserController {

    @Autowired
    private UserService userService;




    @ApiOperation("用户注册")
    @RequestMapping(value = "userRegister",method= RequestMethod.POST)
    public BaseResponse<String> userRegister(User user){

        User name =  userService.findUserName(user);

        if( null != user  &&  null == name  ){
            Boolean result =  userService.save(user);
            return ResultUtils.success(user.getUser_id());
        }else {
            return  ResultUtils.error(40000,"用户名重复");
        }
    }


    @ApiOperation("用户登录")
    @RequestMapping(value="login", method=RequestMethod.POST)
    public BaseResponse<User> userLogin(User user){

        // 条件构造器
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
        // 条件
        queryWrapper.eq("name",user.getName());
        queryWrapper.eq("password", user.getPassword());
        // 根据账号密码调用getOne方法
        User result = userService.getOne(queryWrapper);
        // 如果用户登录状态为1 1为未登录
        if( result.getLoginStatic().equals(1) ){
            // 设置登录状态为0
            user.setLoginStatic(0);
            // 条件构造器
            QueryWrapper<User> wrapper = new QueryWrapper<User>().eq("name",user.getName());
            // 通过用户名修改
            userService.update(user,wrapper);
            return ResultUtils.success(result);
        }else if(result == null){
            return  ResultUtils.error(40000,"账号或密码错误");
        }else {
            return ResultUtils.error(50000, "账号已在别处登录");
        }
    }
}
